package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/thinkeridea/go-extend/exunicode/exutf8"
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"strings"
	"time"
	"unicode/utf8"
)

// 操作日志中间件
func DoLogLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			data    model.AdminLog
			actions []string
		)
		actions = strings.Split(strings.TrimLeft(c.Request.RequestURI, "/"), "/")
		if conv.IsValueInList(actions[len(actions)-1], []string{"add", "update", "delete"}) && conv.IsValueInList(c.Request.Method, []string{"POST", "PUT", "DELETE"}) {
			var content map[string]interface{}
			c.ShouldBindBodyWith(&content, binding.JSON)

			for key, val := range content {
				if utf8.RuneCountInString(conv.String(val)) > 200 {
					content[key] = exutf8.RuneSubString(conv.String(val), 0, 200)
				}
			}

			str, _ := json.Marshal(content)

			data.ApplicationName = actions[0]
			data.Username = "admin"
			data.Ip = utils.GetClientIP(c)
			data.Url = "http://" + c.Request.Host + c.Request.RequestURI
			data.Useragent = c.Request.UserAgent()
			data.Type = 2
			data.CreateTime = time.Now().Unix()
			data.Content = string(str)

			if err := global.DB.Create(&data).Error; err != nil {
				global.LOG.Error(err.Error())
			}
		}
		c.Next()
	}
}
